package com.hp.tiger.chapter3;

import java.util.concurrent.TimeUnit;

/**
 * @author XavierDong
 **/
public class VolatileTest {


    /**
     * 内存可见性，顺序性
     * */
    private volatile static int INT_VALUE = 0;
    private static final int MAX_LIMIT = 5;

    public static void main(String[] args) {

        new Thread(() -> {
            int localValue = INT_VALUE;
            while (localValue < MAX_LIMIT) {
                if (localValue != INT_VALUE) {
                    System.out.printf("The Value updated to [%d]\n", INT_VALUE);
                    localValue = INT_VALUE;
                }
            }
        }, "READER").start();


        new Thread(() -> {
            int localValue = INT_VALUE;
            while (INT_VALUE < MAX_LIMIT) {
                System.out.printf("update the Value to [%d]\n", ++localValue);
                INT_VALUE = localValue;
                try {
                    TimeUnit.MILLISECONDS.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "UPDATED").start();
    }
}
